import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores'

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// 关闭 NProgress 的 loading 效果
NProgress.configure({
  showSpinner: false
})

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      component: () => import('@/views/Login/index.vue'),
      meta: { title: '登录' }
    },
    {
      path: '/',
      component: () => import('@/views/Layout/index.vue'),
      children: [
        {
          path: 'home',
          component: () => import('@/views/Home/index.vue'),
          meta: { title: '首页' }
        },
        {
          path: 'article',
          component: () => import('@/views/Article/index.vue'),
          meta: { title: '健康百科' }
        },
        {
          path: 'notify',
          component: () => import('@/views/Notify/index.vue'),
          meta: { title: '消息通知' }
        },
        {
          path: 'user',
          component: () => import('@/views/User/index.vue'),
          meta: { title: '个人中心' }
        }
      ]
    },
    {
      path: '/user/patient',
      component: () => import('@/views/User/PatientPage.vue'),
      meta: { title: '家庭档案' }
    }
  ]
})

/**
 *  全局前置守卫
 */
router.beforeEach((to, from) => {
  NProgress.start()
  const userStore = useUserStore()
  // 白名单
  const whileList = ['/login']
  if (!userStore.user?.token && !whileList.includes(to.path)) return '/login'
  // 不写或者return true 就是放行
})

/**
 * 全局后置守卫
 */
router.afterEach((to, from) => {
  NProgress.done()
  // 修改标题
  document.title = `优医问诊-${to.meta.title}`
})
export default router
